#!/usr/bin/python
#coding=utf-8
try:
    import json
except:
    import simplejson as json

import urllib2
import json
from PyFetion import PyFetion,sys_encoding

def queryticker(ticker):
    json_str = urllib2.urlopen('http://finance.google.com/finance/info?client=ig&q=%s'%ticker).read()
    dd = json.loads(json_str[6:-3],encoding='latin1')
    return float(dd['l'])



def main():
#add new transaction here
#(code,count,costs,[low_warning,high_warning])
    tks = (
            ('SHA:601899',900,8.002,[9.44,9.90]),
           )
    msg = ''
    for tk_info in tks:
        price = queryticker(tk_info[0])
        print price
        if price == 0:
            continue
        if price > tk_info[3][1]:
            msg += 'high %s %f,gain %f\n '%(tk_info[0],price,tk_info[1]*(price-tk_info[2]))
        elif price < tk_info[3][0]:
            msg += 'low %s %f,gain %f\n '%(tk_info[0],price,tk_info[1]*(price-tk_info[2]))

    if msg != '':
#这个是我的飞信密码，不要乱改哈
        phone = PyFetion("15801207407","?funxv0","TCP")
        try:
            phone.login()
        except PyFetionSupportError,e:
            print u"手机号未开通飞信".encode(sys_encoding)
            sys.exit(0)
        except PyFetionAuthError,e:
            print u"手机号密码错误".encode(sys_encoding)
            sys.exit(0)

        if phone.login_ok:
            print u"登录成功".encode(sys_encoding)
        phone.send_sms(msg,to="15801207407")



import time
if __name__ == '__main__':
    while 1:
        main()
        time.sleep(300)
